<?php
// +----------------------------------------------------------------------
// | OneKeyAdmin [ Believe that you can do better ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2023 http://onekeyadmin.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: MUKE <513038996@qq.com>
// +----------------------------------------------------------------------
namespace plugins\cms\admin\controller;

use think\facade\Db;
use think\facade\View;
use app\admin\BaseController;
use app\admin\model\Catalog;
use app\admin\model\UserGroup;
use app\admin\model\Config;
use plugins\cms\admin\model\Product as ProductModel;
use think\exception\ValidateException;
use plugins\cms\admin\validate\Product as Validate;
/**
 * 产品
 */
class Product extends BaseController
{
    /**
     * 显示资源列表
     */
    public function index()
    {
        if ($this->request->isPost()) {
            $input = input('post.');
            $search = ['catalog', 'keyword', 'status', 'attr', 'product_id'];
            $append = ['attr', 'url'];
            $page = empty($input['page']) ? 1 : $input['page'];
            $pageSize = empty($input['pageSize']) ? 20 : $input['pageSize'];
            $order = ! empty($input['prop']) && ! empty($input['order']) ? [$input['prop'] => $input['order']] : ['istop' => 'desc', 'sort' => 'desc', 'create_time' => 'desc'];
            $count = ProductModel::withSearch($search, $input)->count();
            $data = ProductModel::withSearch($search, $input)->append($append)->with(['spec','sku'])->order($order)->page($page, $pageSize)->select();
            foreach ($data as $key => $value) {
                $value->spec_sku = [$value->spec, $value->sku];
            }
            return json(['status' => 'success','message' => '获取成功', 'data' => $data, 'count' => $count]);
        } else {
            // 权限
            $group = UserGroup::where('status', 1)->order('integral', 'asc')->select();
            // 配置
            $config = Config::getVal('app_cms'); 
            // 分类
            $catalog = Catalog::field('id,pid,title')->where('theme', theme())->where('type', 'product')->where('links_type', 0)->where('status', 1)->order('sort', 'desc')->select()->toArray();
            // 分类pid查询
            foreach ($catalog as $key => $val) {
                if (array_search($val['pid'], array_column($catalog, 'id')) === false) $catalog[$key]['pid'] = 0;
            }
            View::assign([
                'group'   => $group,
                'config'  => $config,
                'catalog' => $catalog,
            ]);
            return View::fetch();
        }
    }

    /**
     * 保存新建的资源
     */
    public function save() 
    {
        if ($this->request->isPost()) {
            try {
                $input = input('post.');
                validate(Validate::class)->scene('save')->check($input);
            } catch ( ValidateException $e ) {
                return json(['status' => 'error', 'message' => $e->getError()]);
            }
            Db::startTrans();
            try {
                $product = ProductModel::create([
                    'group_id'             => $input['group_id'],
                    'catalog_id'           => $input['catalog_id'],
                    'relation'             => $input['relation'],
                    'title'                => $input['title'],
                    'c_title'              => $input['c_title'],
                    'description'          => $input['description'],
                    'content'              => $input['content'],
                    'cover'                => $input['cover'],
                    'images'               => $input['images'],
                    'code'                 => $input['code'],
                    'sale_price'           => $input['sale_price'],
                    'line_price'           => $input['line_price'],
                    'stock'                => $input['stock'],
                    'weight'               => $input['weight'],
                    'seo_url'              => $input['seo_url'],
                    'seo_title'            => $input['seo_title'],
                    'seo_keywords'         => $input['seo_keywords'],
                    'seo_description'      => $input['seo_description'],
                    'parameter'            => $input['parameter'],
                    'field'                => $input['field'],
                    'istop'                => array_search('置顶', $input['attr']) !== false ? 1 : 0,
                    'isrecommend'          => array_search('推荐', $input['attr']) !== false ? 1 : 0,
                    'ishot'                => array_search('热门', $input['attr']) !== false ? 1 : 0,
                    'spec_type'            => $input['spec_type'],
                    'clicks'               => $input['clicks'],
                    'create_time'          => empty($input['create_time']) ? date('Y-m-d H:i:s') : $input['create_time'],
                    'status'               => $input['status'],
                    'sort'                 => $input['sort'],
                ]);
                if ($input['spec_type'] === 1) {
                    foreach ($input['spec_sku'][0] as $key => $val) {
                        $product->spec()->save([
                            'product_id' => $product->id,
                            'title'      => $val['title'],
                            'type'       => $val['type'],
                            'value'      => $val['value'],
                            'sort'       => $key,
                        ]);
                    }
                    foreach ($input['spec_sku'][1] as $key => $val) {
                        $product->sku()->save([
                            'product_id' => $product->id,
                            'title'      => $val['title'],
                            'cover'      => $val['cover'],
                            'code'       => $val['code'],
                            'sale_price' => $val['sale_price'],
                            'line_price' => $val['line_price'],
                            'stock'      => $val['stock'],
                            'weight'     => $val['weight'],
                        ]);
                    }
                }
                Db::commit();
                return json(['status' => 'success', 'message' => '新增成功']);
            } catch (\Exception $e) {
                Db::rollback();
                return json(['status' => 'error', 'message' => '新增失败']);
            }
        }
    }

    /**
     * 保存更新的资源
     */
    public function update() 
    {
        if ($this->request->isPost()) {
            try {
                $input = input('post.');
                validate(Validate::class)->scene('update')->check($input);
            } catch ( ValidateException $e ) {
                return json(['status' => 'error', 'message' => $e->getError()]);
            }
            $product = ProductModel::with(['spec','sku'])->find($input['id']);
            Db::startTrans();
            try {
                $product->group_id            = $input['group_id'];
                $product->catalog_id          = $input['catalog_id'];
                $product->relation            = $input['relation'];
                $product->title               = $input['title'];
                $product->c_title             = $input['c_title'];
                $product->description         = $input['description'];
                $product->content             = $input['content'];
                $product->cover               = $input['cover'];
                $product->images              = $input['images'];
                $product->code                = $input['code'];
                $product->sale_price          = $input['sale_price'];
                $product->line_price          = $input['line_price'];
                $product->stock               = $input['stock'];
                $product->weight              = $input['weight'];
                $product->seo_url             = $input['seo_url'];
                $product->seo_title           = $input['seo_title'];
                $product->seo_keywords        = $input['seo_keywords'];
                $product->seo_description     = $input['seo_description'];
                $product->parameter           = $input['parameter'];
                $product->field               = $input['field'];
                $product->istop               = array_search('置顶', $input['attr']) !== false ? 1 : 0;
                $product->isrecommend         = array_search('推荐', $input['attr']) !== false ? 1 : 0;
                $product->ishot               = array_search('热门', $input['attr']) !== false ? 1 : 0;
                $product->spec_type           = $input['spec_type'];
                $product->clicks              = $input['clicks'];
                $product->create_time         = empty($input['create_time']) ?  : $input['create_time'];
                $product->status              = $input['status'];
                $product->sort                = $input['sort'];
                $product->save();
                if ($input['spec_type'] === 1) {
                    foreach ($input['spec_sku'][0] as $key => $val) {
                        $exist = $product->spec()->where('product_id', $product->id)->where('title',$val['title'])->find();
                        if ($exist) {
                            $exist->type  = $val['type'];
                            $exist->value = $val['value'];
                            $exist->sort  = $key;
                            $exist->save();
                        } else {
                            $product->spec()->save([
                                'product_id' => $product->id,
                                'title'      => $val['title'],
                                'type'       => $val['type'],
                                'value'      => $val['value'],
                                'sort'       => $key,
                            ]);
                        }
                    }
                    foreach ($input['spec_sku'][1] as $key => $val) {
                        $exist = $product->sku()->where('product_id', $product->id)->where('title',$val['title'])->find();
                        if ($exist) {
                            $exist->cover          = $val['cover'];
                            $exist->code           = $val['code'];
                            $exist->sale_price     = $val['sale_price'];
                            $exist->line_price     = $val['line_price'];
                            $exist->stock          = $val['stock'];
                            $exist->weight         = $val['weight'];
                            $exist->save();
                        } else {
                            $product->sku()->save([
                                'product_id'       => $product->id,
                                'title'          => $val['title'],
                                'cover'          => $val['cover'],
                                'code'           => $val['code'],
                                'sale_price'     => $val['sale_price'],
                                'line_price'     => $val['line_price'],
                                'stock'          => $val['stock'],   
                                'weight'         => $val['weight'],  
                            ]);
                        }
                    }
                }
                Db::commit();
                return json(['status' => 'success', 'message' => '修改成功']);
            } catch (\Exception $e) {
                Db::rollback();
                return json(['status' => 'error', 'message' => '修改失败']);
            }
        }
    }

    /**
     * 删除指定资源
     */
    public function delete() 
    {
        if ($this->request->isPost()) {
            Db::startTrans();
            try {
                $product = ProductModel::with(['spec','sku'])->whereIn('id', input('post.ids'))->select();
                foreach ($product as $v) {
                   $v->together(['spec','sku'])->delete();
                }
                Db::commit();
                return json(['status' => 'success', 'message' => '删除成功']);
            } catch (\Exception $e) {
                Db::rollback();
                return json(['status' => 'error', 'message' => '删除失败']);
            }
        }
    }
}